package com.bdqn.intercept;


import com.bdqn.util.ResponseUtil;
import com.bdqn.util.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器处理token令牌
 */
public class TokenIntercept  extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String accep = request.getHeader("Accept");
        boolean flag = false;
        if (StringUtils.isNotBlank(accep)){
           if (accep.startsWith("application/json") || accep.equals("*/*")){
               flag=true;
           }
        }
        String token = request.getParameter("token");
        String sessionToken = (String)request.getSession().getAttribute("token");
        if (StringUtils.isBlank(token) || StringUtils.isBlank(sessionToken)  || !sessionToken.equals(token)){
                if (flag){
                    ResponseUtil.sendJson(response, Result.createError("非法操作"));
                }else {
                    ResponseUtil.alertRedirect(response,"非法操作","/");
                }

            return  false;
        }
        return true;
    }

}
